package com.zut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zut.mapper.LinkMapper;
import com.zut.pojo.Link;
import com.zut.pojo.Manager;
import com.zut.pojo.MyPage;
import com.zut.pojo.Result;
import com.zut.service.LinkService;
import com.zut.utils.DateUtil;
import com.zut.utils.NumUtil;
import com.zut.utils.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.List;


/**
 * @author: Mr.Liu
 * @create: 2021-11-13 13:10
 */
@Service
public class LinkServiceImpl implements LinkService {

    private static final Logger logger = LoggerFactory.getLogger(LinkServiceImpl.class);

    @Autowired
    @Qualifier("myRedisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    LinkMapper linkMapper;

    @Value("${projectHost}")
    private String projectHost;

    @Autowired
    UserUtil userUtil;

    @Autowired
    DateUtil dateUtil;

    @Override
    public Result createLinkId(String longLink, HttpServletRequest request, int length) {
        if (longLink == null || "".equals(longLink)) {
            return Result.error("链接不能为空");
        }
        Link l = linkMapper.selectOne(new QueryWrapper<Link>().eq("data", longLink));

        if (l != null && l.getDeleted() != 1) {
            return Result.success("已经创建过", projectHost + "/find/" + l.getId());
        }
        Link link = new Link();
        int i = 0;
        String linkId = null;
        while (i < 10000) {
            linkId = NumUtil.Rom(length);
            link = linkMapper.selectOne(new QueryWrapper<Link>().eq("id", linkId));
            if (link == null) {
                //保存哪个用户创建的
                Integer uuid = userUtil.getUserId(request);
                //如果没有登录就填0
                if (uuid == null) {
                    uuid = 0;
                }
                //存入Redis中
                redisTemplate.opsForValue().set(linkId, longLink);
                linkMapper.insert(new Link(linkId, longLink, 0,
                        dateUtil.getDate(), dateUtil.getDate(), uuid, 0));
                return Result.success("创建成功", projectHost + "/find/" + linkId);
            }
            i++;
        }
        return Result.error("创建失败");
    }

    @Override
    public String findId(String id) {
        Link link = null;
        Integer num = null;
        //先看Redis中是否有值
        String redisLink = (String) redisTemplate.opsForValue().get(id);
        //命中
        if (redisLink != null) {
            link = linkMapper.selectOne(new QueryWrapper<Link>().eq("id", id));
            num = link.getNum();
            link.setNum(++num);
            link.setGmtModified(dateUtil.getDate());
            int i = linkMapper.updateById(link);
            if (i == 1) {
                logger.info("更新链接访问次数成功");
            } else {
                logger.warn("更新链接访问次数失败");
            }
            //更新登录统计
            try {
                dateUtil.saveTime();
            } catch (ParseException e) {
                logger.warn("更新时间戳出问题了！");
                e.printStackTrace();
            }
            return "redirect:" + redisLink;
        }
        //未命中的话
        link = linkMapper.selectOne(new QueryWrapper<Link>().eq("id", id));

        if (link != null && link.getDeleted() == 0) {
            num = link.getNum();
            link.setNum(++num);
            link.setGmtModified(dateUtil.getDate());
            int i = linkMapper.updateById(link);
            if (i == 1) {
                logger.info("更新链接访问次数成功");
            } else {
                logger.warn("更新链接访问次数失败");
            }
            //
            redisTemplate.opsForValue().set(link.getId(), link.getData());
            return "redirect:" + link.getData();
        }
        return "redirect:" + "https://www.baidu.com";
    }

    @Override
    public Result getAllLink(Integer current) {
        if ("".equals(current) || current == null) {
            return Result.error("当前页不能为空");
        }
        Page<Link> linkPage = new Page<>(current, 7);
        Page<Link> selectPage = linkMapper.selectPage(linkPage, new QueryWrapper<Link>().eq("deleted", "0"));
        MyPage<Link> linkMyPage = new MyPage<Link>(current, selectPage.getTotal(), selectPage.getPages(), selectPage.getRecords());
        return Result.success("分页查询成功！", linkMyPage);
    }

    @Override
    public Result deleteLink(String id, HttpServletRequest request) {
        if (id == null || "".equals(id)) {
            return Result.error("id为空，删除失败");
        }
        //判断是不是管理员，如果是就可以直接删除
        Manager manager = userUtil.getManager(request);
        if (manager.getAuths().lastIndexOf("admin") >= 0) {
            int i = linkMapper.updateById(new Link(id, null, null, null, dateUtil.getDate(), null, 1));
            //清除Redis中的数据
            redisTemplate.delete(id);

            if (i == 1) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } else {
            //如果不是管理员就判断这个链接是不是本人的链接，如果是就删除
            Link link = linkMapper.selectOne(new QueryWrapper<Link>().eq("id", id));
            if (link.getUuid() == manager.getId()) {
                int i = linkMapper.updateById(new Link(id, null, null, null, dateUtil.getDate(), null, 1));
                if (i == 1) {
                    return Result.success("删除成功");
                } else {
                    return Result.error("删除失败");
                }
            }
        }
        return Result.error("没有权限删除");
    }

    @Override
    public Result createVipLink(String id, String longLink, HttpServletRequest request) {
        if (id == null || "".equals(id) || longLink == null || "".equals(longLink)) {
            return Result.error("id或链接不能为空");
        }
        Link link = linkMapper.selectOne(new QueryWrapper<Link>().eq("id", id));
        if (link != null) {
            return Result.error("id已被使用");
        }
        Integer uuid = userUtil.getUserId(request);
        logger.info("定制次链接的用户是：{}", uuid);

        int i = linkMapper.insert(new Link(id, longLink, 0, dateUtil.getDate(), dateUtil.getDate(), uuid, 0));
        if (i == 1) {
            return Result.success("创建成功，快去使用吧");
        }
        return Result.error("未知错误，请联系管理员");
    }

    @Override
    public List<Link> topTen() {
        return linkMapper.selectList(new QueryWrapper<Link>()
                .orderByDesc("num")
                .select("id", "data", "num")
                .eq("deleted", 0)
                .last("limit 10"));
    }

    @Override
    public List<Link> getLinkByUserId(HttpServletRequest request) {
        Integer userId = userUtil.getUserId(request);
        return linkMapper.selectList(new QueryWrapper<Link>().eq("uuid", userId)
                .eq("deleted", 0));
    }
}
